﻿using System.Reflection;

namespace Xms.Abp;

public abstract class ViewModelBase: IValidatableObject
{
    [Display(Name = "乐观锁戳")]
    public virtual string ConcurrencyStamp { get; set; }

    public virtual IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        var type = GetType();
        var properties = type.GetProperties();
        var result = new List<ValidationResult>();
        foreach (var property in properties)
        {
            CheckAttribute<MobilePhoneAttribute>(property, Check.IsValidateMobilePhone, result, "手机号码");
            CheckAttribute<PhoneAttribute>(property, Check.IsValidatePhone, result, "电话号码");
            CheckAttribute<EmailAttribute>(property, Check.IsValidateEmail, result, "邮箱地址");
            CheckAttribute<NoAttribute>(property, Check.IsValidateNo, result, "编号格式");
            CheckAttribute<StrongPasswordAttribute>(property, Check.IsValidateStrongPassword, result, "密码必须是包含数字、大小写字母、特殊字符且长度为6到16位的字符");
        }
        return result;
    }

    private void CheckAttribute<TAttribute>(PropertyInfo property, Func<string, bool> validator, List<ValidationResult> result, string displayName = null, string errorMessage = null)
        where TAttribute : Attribute
    {
        if (property.GetCustomAttribute<TAttribute>() != null)
        {
            var value = (string)property.GetValue(this);
            if (!value.IsNullOrWhiteSpace() && !validator(value))
            {
                if (errorMessage.IsNullOrWhiteSpace())
                {
                    var displayAttr = property.GetCustomAttribute<DisplayAttribute>();
                    displayName = displayAttr?.Name ?? displayName;
                    errorMessage = displayName + "不正确";
                }
                result.Add(new ValidationResult(errorMessage, new[] { property.Name }));
            }
        }
    }
}
